/**
 * 卖家商品类
 * @type {*|exports|module.exports}
 */
var AV = require('leanengine');
// 状态  0代表flase，1代表true
var rState="";	
var rCode="";
// 如有错误或异常，该列才有值
var rMsg="";
// 通用返回对象
var rResult = "";
var err;
var common   = require( '../cloud/common' );
var apis = require( '../cloud/lib/apis' );
var async=require( "async" );

var shopAccountVerifyJS = require('../cloud/shopAccountVerify');

/**
 * 检查商品库存及限购情况
 * @param goodsOId 商品标识
 * @param modelOId 型号标识
 * @param cb
 */
exports.checkGoodsStock=checkGoodsStock;
function checkGoodsStock(modelAndNumArray,cb){
	var modelOIds=[];
	var modelNumMap={};
	  for ( var i = 0; i < modelAndNumArray.length; i++) {
		  modelOIds.push(modelAndNumArray[i]["modelOId"]);
		  modelNumMap[modelAndNumArray[i]["modelOId"]]=modelAndNumArray[i]["num"];
	 }
	  //查询商品型号数据 
	  var goodsModelQuery = new AV.Query('Shop_goods_model_stock');
	  goodsModelQuery.containedIn("objectId", modelOIds);
	  goodsModelQuery.limit(1000);
	  goodsModelQuery.include("goodsObj");
	  goodsModelQuery.include("goodsObj.shopObj");
	  goodsModelQuery.find({
	    	success: function(modelObjs) {
	    		if(modelObjs.length!=modelAndNumArray.length){
	    			return cb(0,"型号数据异常，请刷新后重试",null);
	    		}else{
	    			var state=1;
	    			var msg="";
	    			for ( var i = 0; i < modelObjs.length; i++) {
		    			if(modelObjs[i].get("goodsObj")!=null){
		    				if(modelObjs[i].get("goodsObj").get("status")!=apis["goods"]["status_normal"]){
		    					state=0;
		    					msg=modelObjs[i].get("goodsObj").get("title")+" 已下架或删除";
		    					break;
		    				}
		    				if(modelObjs[i].get("goodsObj").get("shopObj")==null){
			    				state=0;
				    			msg=modelObjs[i].get("goodsObj").get("title")+" 所在店铺不存在";
				    			break;
		    				}
		    				if(modelObjs[i].get("goodsObj").get("shopObj").get("status")!="1"){
			    				state=0;
					    		msg=modelObjs[i].get("goodsObj").get("title")+" 所在店铺已关闭";
					    		break;
		    				}
		    				if(modelObjs[i].get("numPurchase")!=null&&modelObjs[i].get("numPurchase")!=""){
		    					if(modelObjs[i].get("numPurchase")<modelNumMap[modelObjs[i].id]){
				    				state=0;
							    	msg=modelObjs[i].get("goodsObj").get("title")+"  每次限购"+modelObjs[i].get("numPurchase")+"件";
							    	break;
		    					}
	    					}
		    				if(modelObjs[i].get("stock")<modelNumMap[modelObjs[i].id]){
			    				state=0;
						    	msg=modelObjs[i].get("goodsObj").get("title")+"  库存只有"+modelObjs[i].get("stock")+"件";
						    	break;
		    				}
		    		}else{
			    		state=0;
		    			msg="错误的商品型号";
		    			break;
		    		}
	    		}
	    		return cb(state,msg,modelObjs);
	    		}
	    	},error:function(error){
	    		return cb(0,error.message,null);
	    	}
	  })
}
AV.Cloud.beforeSave('Shop_goods', function(request, response) {
	var title=request.object.get("title");
	if(title==undefined||title==null)
		title="";
	if(title!=""){
		title=title.toLowerCase();
	}
	request.object.set("searchVal",title);
	return response.success();
});
//商品更新后事件
AV.Cloud.afterUpdate('Shop_goods', function(request) {
	if(request.object.get("_updatedKeys").indexOf("title")>-1){
			var isUpdate=false;
			var title=request.object.get("title");
			if(title==undefined||title==null)
				title="";
			if(title!=""){
				title=title.toLowerCase();
			}
			if(title!=request.object.get("searchVal")){
				request.object.set("searchVal",title);
				request.object.save();
			}
	}
});
AV.Cloud.beforeSave('Shop_shop', function(request, response) {
	var name=request.object.get("name");
	if(name==undefined||name==null)
		name="";
	if(name!=""){
		name=name.toLowerCase();
	}
	request.object.set("searchVal",name);
	return response.success();
});
AV.Cloud.afterUpdate('Shop_shop', function(request) {
	if(request.object.get("_updatedKeys")!=null){
		if(request.object.get("_updatedKeys").indexOf("name")>-1){
				var isUpdate=false;
				var name=request.object.get("name");
				if(name==undefined||name==null)
					name="";
				if(name!=""){
					name=name.toLowerCase();
				}
				if(name!=request.object.get("searchVal")){
					request.object.set("searchVal",name);
					request.object.save();
				}
		}
	}
});
exports.searchGoodsSysCategory=searchGoodsSysCategory;
/**
 * 查询商品分类
 * @param name 商品名称
 * @param callback
 */
function searchGoodsSysCategory(name,callback){
	if(name==null||name==""||name==undefined){
		return callback(0,null,null); 
	}else{
		var query=new AV.Query('Shop_good_type');
		query.equalTo("name",name);
		query.first({
			  success: function(goodTypeObj) {
				  if(goodTypeObj==null){
					  return callback(0,null,null);
				  }else{
					  return callback(1,goodTypeObj.get("code"),goodTypeObj.get("level"));
				  }
			  },error:function(error){
				  return callback(0,null,null);
			  }
		});
	}
}
/**
 * 添加商品
 * @param pics 图片数组(第一张默认为封面图)
 * @param title 商品名称
 * @param description 商品说明
 * @param priceModelStocks 库存价格型号数组
 * @param goodType 系统商品类型
 * @param shopType 店铺商品类型
 * @param recommend 是否推荐，0不推荐 1推荐
 * @param freePost 是否包邮，0不包邮 1包邮
 * @param callback
 */
function addGoods(request,callback ) {
	var uId=request.user.id;
	var pics=request.params.pics;
	var title=request.params.title;
	var describe=request.params.describe;
	var price=request.params.price;
	var promotionPrice=request.params.promotionPrice;//推广价格
	var modelStocks=request.params.modelStocks;
	var goodType=request.params.goodType;
	var shopType=request.params.shopType;
	var recommend=request.params.recommend;
	var freePost=request.params.freePost;
	var promote=request.params.promote;
    var groupBuying=request.params.groupBuying;
    var groupPrice=request.params.groupPrice;
	var discount=request.params.discount;
	var label=request.params.label;
	var originalPrice=request.params.originalPrice;
	var groupCommission=request.params.groupCommission;

	var customize = request.params.customize;//是否可以定制
	if(promote==""||promote==undefined||promote==null){
		promote=0;
	}else{
		promote=common.formatMoney(parseInt(promote)/100);
	}
	if(customize !=null && customize != undefined && parseInt(customize) == 1){
		customize=1;
	}else{
		customize=-1;
	}
	if(isNaN(promote)){
		promote=0;
	}
	price=common.formatMoney(price);
	if(price>99999999)
		price=99999999;
	if(promotionPrice!=""||promotionPrice!=null||promotionPrice!=undefined){
		promotionPrice=common.formatMoney(promotionPrice);
	}else{
		promotionPrice=price;
	}
	price=common.formatMoney(price);
	var promotePrice=common.formatMoney(price*promote);
	if(shopType==null||shopType==undefined)
		shopType="";
	else
		shopType=shopType.toString();
	if(groupCommission==null||groupCommission==""||groupCommission=="undefined")
		groupCommission=0;
	else
		groupCommission=parseFloat(groupCommission);
	if(recommend==null||recommend==""||recommend=="undefined")
		recommend="0";
	else
		recommend=recommend.toString();
	if(freePost==null||freePost==""||freePost=="undefined")
		freePost="0";
	else
		freePost=freePost.toString();
	if(discount==null||discount==""||discount=="undefined")
		discount=0;
	else
		discount=parseFloat(discount);
	if(originalPrice==null||originalPrice==""||originalPrice=="undefined")
		originalPrice=0;
	else
		originalPrice=parseFloat(originalPrice);
	if(label==null||label==""||label=="undefined")
		label="";
	if(groupBuying==null||groupBuying==""||groupBuying==undefined){
        groupBuying=1;
	}
    if(groupPrice==null||groupPrice==""||groupPrice==undefined){
        groupPrice=0;
    }
	//查询是否拥有店铺
	findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			if(shopObj.get("status")=="0"){
				return callback(null,JSON.stringify(common.getErrArr("您的店铺已被关闭")));
			}else{
				//对pics和modelStocks进行去重
				pics=common.arrayDistinctStr(pics);
				modelStocks=common.arrayDistinctStr(modelStocks);
				//创建商品对象
				var ShopGoods = common.getEntity("Shop_goods");
				var goodsObj = new ShopGoods();
				//初始化商品参数
				goodsObj.set("collectionNum", 0);
				goodsObj.set("saleNums", 0);


				shopAccountVerifyJS.verifyStatus(request.user.id, function (error, verifyObj) {

					if (verifyObj != null) {

						if (verifyObj.get("shopStatus") != "" && verifyObj.get("shopStatus") != null && verifyObj.get("shopStatus") != undefined && verifyObj.get("shopStatus") != "1") {
							goodsObj.set("status", 2);

						}else{
							goodsObj.set("status", 1);
						}
					}else{
						goodsObj.set("status", 1);
					}

					goodsObj.set("promote", promote);
					goodsObj.set("promotePrice", common.formatMoney(price*promote));
					goodsObj.set("promotionPrice", promotionPrice);
					goodsObj.set("shopOId", shopObj.id);
					goodsObj.set("shopObj", shopObj);
					goodsObj.set("recommend", recommend);
					goodsObj.set("freePost", freePost);
					goodsObj.set("sellerOId", uId);
					goodsObj.set("sellerObj", request.user);
					goodsObj.set("title", title);
					goodsObj.set("describe", describe);

                    goodsObj.set("groupBuying", Number(groupBuying));
                    goodsObj.set("groupPrice", Number(groupPrice));
					goodsObj.set("discount", discount);
					goodsObj.set("originalPrice", originalPrice);
					goodsObj.set("label", label);

					goodsObj.set("sysCategory", goodType);//系统商品类型
					goodsObj.set("shopCategory", shopType);//店铺商品类型
					goodsObj.set("price", price);//销售价格
					goodsObj.set("customize", customize);
					goodsObj.set("groupCommission", groupCommission);
					if(pics[0]["objectId"]!=null)
						goodsObj.set("picName",pics[0]["objectId"]);
					//保存商品对象
					goodsObj.save(null, {
						success : function(goodSaveObj) {
							//保存商品型号和库存
							for ( var i = 0; i < modelStocks.length; i++) {
								//如果没有属性则添加一条默认属性
								if(modelStocks[i]["model"]==null||modelStocks[i]["model"]==" "||modelStocks[i]["model"]==undefined){
									modelStocks[i]["model"]="";
								}
							}
							//保存商品样式图
							saveGoodsPics(goodSaveObj,pics,function(err,count){
								if(err){
									return callback(null,JSON.stringify(common.getErrArr(err)));
								}else{
									//保存商品型号
									saveModelStocks(goodSaveObj,modelStocks,function(err,count){
										if(err){
											return callback(null,JSON.stringify(common.getErrArr(err)));
										}else{
											var result={};
											result["goodsOId"]=goodSaveObj.id;
											var returnArr=common.getReturnArr("1","1000","",result);
											return callback(null,JSON.stringify(returnArr));
										}
									})
								}
							})
						},
						error : function(errObj,error) {
							return callback(null,JSON.stringify(common.getErrArr(error)));
						}
					});


				});

			}
		}
	})
}
/**
 * 编辑商品
 * @param pics 图片数组(第一张默认为封面图)
 * @param title 商品名称
 * @param description 商品说明
 * @param priceModelStocks 库存价格型号数组
 * @param goodType 系统商品类型
 * @param shopType 店铺商品类型
 * @param recommend 是否推荐，0不推荐 1推荐
 * @param freePost 是否包邮，0不包邮 1包邮
 * @param callback
 */
function editGoods(request,callback ) {
	var goodsOId=request.params.goodsOId;
	if(goodsOId==""||goodsOId==null||goodsOId==undefined){
		return callback(null,JSON.stringify(common.getErrArr("错误的参数")));
	}
	var uId=request.user.id;
	var pics=request.params.pics;
	var title=request.params.title;
	var describe=request.params.describe;
	var price=request.params.price;
	var promotionPrice=request.params.promotionPrice;
	var modelStocks=request.params.modelStocks;
	var goodType=request.params.goodType;
	var shopType=request.params.shopType;
	var recommend=request.params.recommend;
    var groupBuying=request.params.groupBuying;
    var groupPrice=request.params.groupPrice;
	var freePost=request.params.freePost;
	var promote=request.params.promote;
	var customize = request.params.customize;
	var promotePrice=0;

	var discount=request.params.discount;
	var label=request.params.label;
	var originalPrice=request.params.originalPrice;
	var groupCommission=request.params.groupCommission;


	if(promote!=null&&promote!=undefined){
		promote=common.formatMoney(parseInt(promote)/100);
	}else{
		promote="";
	}

	if(customize !=null && customize != undefined && parseInt(customize) == 1){
		customize=1;
	}else{
		customize=-1;
	}

	if(isNaN(promote)){
		promote="";
	}
	if(price!=""&&price!=null&&price!=undefined){
		if(price>99999999)
			price=99999999;
		price=common.formatMoney(price);
	}
	if(recommend==null||recommend==""||recommend==undefined)
		recommend=null;
	if(freePost==null||freePost==""||freePost==undefined)
		freePost=null;


	if(discount==null||discount==""||discount=="undefined")
		discount=0;
	else
		discount=parseFloat(discount);
	if(originalPrice==null||originalPrice==""||originalPrice=="undefined")
		originalPrice=0;
	else
		originalPrice=parseFloat(originalPrice);
	if(label==null||label==""||label=="undefined")
		label="";


	//查询商品
	getGoodsByOId(goodsOId,function(goodsObj){
		if(goodsObj==null){
			return callback(null,JSON.stringify(common.getErrArr("无效的商品")));
		}else{
			if(goodsObj.get("sellerOId")!=uId){
				return callback(null,JSON.stringify(common.getErrArr("无权操作")));
			}else{
				//对pics和modelStocks进行去重
				pics=common.arrayDistinctStr(pics);
				modelStocks=common.arrayDistinctStr(modelStocks);
				//更新商品对象
				if(customize) {//是否可以定制
					goodsObj.set("customize", customize);
				}
				if (groupBuying!=null&&groupBuying!=undefined){
                    goodsObj.set("groupBuying", Number(groupBuying));
				}
                if (groupPrice!=null&&groupPrice!=undefined){
                    goodsObj.set("groupPrice", Number(groupPrice));
                }
				if(recommend!=null&&recommend!=undefined)
					goodsObj.set("recommend", recommend);
				if(freePost!=null&&freePost!=undefined)
					goodsObj.set("freePost", freePost);
				if(promote!=undefined&&promote!=null)
					goodsObj.set("promote", promote);
				if(title!=null&&title!=undefined)
					goodsObj.set("title", title);
				if(describe!=null&&describe!=undefined)
					goodsObj.set("describe", describe);
				if(goodType!=null&&goodType!=undefined)
					goodsObj.set("sysCategory", goodType);//系统商品类型
				if(shopType!=null&&shopType!=undefined)
					goodsObj.set("shopCategory", shopType);//店铺商品类型
				if(price!=null&&price!=undefined)
					goodsObj.set("price", price);//销售价格
				if(groupCommission!=null&&groupCommission!=undefined)
					goodsObj.set("groupCommission",parseFloat(groupCommission));
				if(pics!=null&&pics!=undefined)
					goodsObj.set("picName",pics[0]["objectId"]);
				if(promotionPrice!=null||promotionPrice!=undefined){
					promotionPrice=common.formatMoney(promotionPrice);
				}else{
					promotionPrice=price;
				}

				goodsObj.set("discount", discount);
				goodsObj.set("originalPrice", originalPrice);
				goodsObj.set("label", label);


				goodsObj.set("promotionPrice", promotionPrice);
				//计算新佣金
				goodsObj.set("promotePrice",common.formatMoney(goodsObj.get("price")*goodsObj.get("promote")));
				//更新商品对象
				goodsObj.save(null, {
						success : function(goodSaveObj) {
							//更新商品型号和库存
							for ( var i = 0; i < modelStocks.length; i++) {
								//如果没有属性则添加一条默认属性
								if(modelStocks[i]["model"]==null||modelStocks[i]["model"]==""){
									modelStocks[i]["model"]="默认规格";
								}
							}
									//保存商品新型号(如存在则不变化)
									saveModelStocks(goodSaveObj,modelStocks,function(err,count){
										if(err){
											return callback(null,JSON.stringify(common.getErrArr(err)));
										}else{
											//保存商品新样式图
											saveOrUpdateGoodsPics(goodSaveObj,pics,function(err,count){
												if(err){
													return callback(null,JSON.stringify(common.getErrArr(err)));
												}else{
													var result={};
													result["goodsOId"]=goodSaveObj.id;
													var returnArr=common.getReturnArr("1","1000","",result);
													return callback(null,JSON.stringify(returnArr)); 
				 								}
											})
										}
									})
						},
						error : function(errObj,error) {
							return callback(null,JSON.stringify(error));
						}
					});
			}
		}
	})
}

/**
 * 删除
 * @param request
 * @param callback
 */
function delGoods(request,callback ) {
	var goodsOIds=request.params.goodsOIds;
	var uId=request.user.id;
	//查询可删除商品
	getGoodsByOIds(uId,goodsOIds,[0,1],function(goodsObjs){
		for ( var i = 0; i < goodsObjs.length; i++) {
			goodsObjs[i].set("status",-1);
		}
		 AV.Object.saveAll(goodsObjs, function(list, error) {
			 if(list){
				 return callback(null,JSON.stringify(common.getReturnArr("1","1000","",""))); 
			 }else{
				 return callback(null,JSON.stringify(common.getReturnArr("0","1000","",""))); 
			 }
		 });
	})
};
/**
 * 下架商品
 * @param request
 * @param callback
 */
function offGoods(request,callback ) {
	var goodsOIds=request.params.goodsOIds;
	var uId=request.user.id;
	//查询可下架商品
	getGoodsByOIds(uId,goodsOIds,[1,2],function(goodsObjs){
		for ( var i = 0; i < goodsObjs.length; i++) {
			goodsObjs[i].set("status",0);
		}
		 AV.Object.saveAll(goodsObjs, function(list, error) {
			 if(list){
				 return callback(null,JSON.stringify(common.getReturnArr("1","1000","",""))); 
			 }else{
				 return callback(null,JSON.stringify(common.getReturnArr("0","1000","",""))); 
			 }
		 });
	})
};
/**
 * 上架商品
 * @param request
 * @param callback
 */
function onGoods(request,callback ) {
	var goodsOIds=request.params.goodsOIds;
	var uId=request.user.id;
	//查询可上架商品


	shopAccountVerifyJS.verifyStatus(request.user.id, function (error, verifyObj) {
		var status = 1;
		if (verifyObj != null) {

			if (verifyObj.get("shopStatus") != "" && verifyObj.get("shopStatus") != null && verifyObj.get("shopStatus") != undefined && verifyObj.get("shopStatus") != "1") {
				status = 2;
			}
		}

		getGoodsByOIds(uId,goodsOIds,[0],function(goodsObjs){
			for ( var i = 0; i < goodsObjs.length; i++) {
				goodsObjs[i].set("status",status);
			}
			AV.Object.saveAll(goodsObjs, function(list, error) {
				if(list){
					var returnArr=common.getReturnArr("1","1000","","");
					return callback(null,JSON.stringify(returnArr));
				}else{
					var returnArr=common.getReturnArr("0","1000","","");
					return callback(null,JSON.stringify(returnArr));
				}
			});
		})

	});


};
/**
 * 前往编辑商品
 * @param request
 * @param callback
 */
function goEditGoods(request,callback ) {
	var goodsOId=request.params.goodsOId;
	var uId=request.user.id;
	//查询商品
	getGoodsByOId(goodsOId,function(goodsObj){
		if(goodsObj==null){
			return callback(null,JSON.stringify(common.getErrArr("不存在此商品")));
		}else{
			if(goodsObj.get("sellerOId")!=uId){
				return callback(null,JSON.stringify(common.getErrArr("无权操作")));
			}else{
				if(goodsObj.get("status")==-1){
					return callback(null,JSON.stringify(common.getErrArr("无效的商品")));
				}else{
				//查询商品基本信息
				var goodsBaseInfo=common.getEditGoodsBaseInfo(goodsObj);
				//查询商品图片信息
				findGoodsPicByGoodsOId(goodsObj.id,function(goodsPics){
					var goodsPicArry=[];
					var picMap=null;
					for ( var i = 0; i < goodsPics.length; i++) {
						picMap=common.getGoodsPic(goodsPics[i]);
						if(picMap!=null&&picMap!={})
							goodsPicArry.push(picMap)
					}
					 //查询商品型号信息
					findGoodsModelByGoodsOId(goodsObj.id,function(goodsModels){
						var goodsModelArry=[];
						for ( var i = 0; i < goodsModels.length; i++) {
							var modelObj={};
							modelObj["model"]=goodsModels[i].get("model");
							modelObj["stock"]=goodsModels[i].get("stock");
							goodsModelArry.push(modelObj);
						}
						
//						//查询商品系统分类和店铺分类
						getShopCategoryName(goodsBaseInfo["shopCategory"],function(shopCategoryObj){
							if(shopCategoryObj==null){
								goodsBaseInfo["shopCategoryName"]="";
							}else{
								goodsBaseInfo["shopCategoryName"]=shopCategoryObj.get("name");
							}
							getSysCategoryName(goodsBaseInfo["sysCategory"],function(sysCategoryObj){
								if(sysCategoryObj==null){
									goodsBaseInfo["sysCategoryName"]="";
								}else{
									goodsBaseInfo["sysCategoryName"]=sysCategoryObj.get("name");
								}
								//返回商品
								var result={};
								result["baseInfo"]=goodsBaseInfo;
								result["pics"]=goodsPicArry;
								result["modelStocks"]=goodsModelArry;
								var returnArr=common.getReturnArr("","1000","",result);
								return callback(null,JSON.stringify(returnArr));
							})
						})
						
					})
				})
				}
			}
		}
	});
}
exports.getShopCategoryName=getShopCategoryName;
function getShopCategoryName(shopCategoryOId,callback){
	if(shopCategoryOId==""||shopCategoryOId==null||shopCategoryOId==undefined){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_shop_type');
		query.equalTo("objectId", shopCategoryOId);
		query.first({
			success : function(shopCategoryObj) {
				return callback(shopCategoryObj);
			},error:function(error){
				return callback(null);
			}
		});
	}
}
exports.getSysCategoryName=getSysCategoryName;
function getSysCategoryName(sysCategoryOId,callback){
	if(sysCategoryOId==""||sysCategoryOId==null||sysCategoryOId==undefined){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_good_type');
		query.equalTo("code", sysCategoryOId);
		query.first({
			success : function(sysCategoryObj) {
				return callback(sysCategoryObj);
			},error:function(error){
				return callback(null);
			}
		});
	}
}
/**
 * 查询商品样式图
 * @param goodsOId
 * @returns
 */
exports.findGoodsPicByGoodsOId=findGoodsPicByGoodsOId;
function findGoodsPicByGoodsOId(goodsOId,callback){
	if(goodsOId==""||goodsOId==null||goodsOId==undefined){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_goodsPic');
		query.equalTo("goodsOId", goodsOId);
		query.ascending("sortNum");
		query.find({
			success : function(shopGoodsPics) {
				return callback(shopGoodsPics);
			},
			   error: function(err){
				   return callback(null);
			   }
		});
	}
}
/**
 * 查询商品型号
 * @param goodsOId
 * @returns
 */
exports.findGoodsModelByGoodsOId=findGoodsModelByGoodsOId;
function findGoodsModelByGoodsOId(goodsOId,callback){
	if(goodsOId==""||goodsOId==null){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_goods_model_stock');
		query.equalTo("goodsOId", goodsOId);
		query.ascending("sortNum");
		query.find({
			success : function(shopGoodsModels) {
				return callback(shopGoodsModels);
			},
			   error: function(err){
				   return callback([]);
			   }
		});
	}
}
/**
 * 根据商品标识查询商品
 * @param goodsOIds
 * @param callback
 * @returns
 */
exports.getGoodsByOIds = getGoodsByOIds;
function getGoodsByOIds(uId,goodsOId,status,callback){
		//去重
		goodsOId=common.arrayDistinctStr(goodsOId);
		var query = new AV.Query('Shop_goods');
		if(uId!=""&&uId!=null&&uId!=undefined)
			query.equalTo("sellerOId", uId);
		if(status!=""&&status!=null&&status!=undefined)
			query.containedIn("status",status);
		query.containedIn("objectId",goodsOId);
		query.find({
			success : function(goodsObjs) {
				return callback(goodsObjs);
			},error:function(error){
				return callback([]);
			}
		});
}
exports.getGoodsByOId = getGoodsByOId;
/**
 * 根据商品标识查询商品
 * @param goodsOId
 * @param callback
 * @returns
 */
function getGoodsByOId(goodsOId,callback){
	if(goodsOId==""||goodsOId==null||goodsOId==undefined){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_goods');
		query.equalTo("objectId", goodsOId);
		query.include("sellerObj")
		query.first({
			success : function(object) {
				return callback(object);
			},error:function(error){
				return callback(null);
			}
		});
	}
}
exports.getShopCategoryByOId = getShopCategoryByOId;
/**
 * 根据商品标识查询商品
 * @param goodsOId
 * @param callback
 * @returns
 */
function getShopCategoryByOId(shopCategory,callback){
	if(shopCategory==""||shopCategory==null||shopCategory==undefined){
		return callback(null);
	}else{
		if(shopCategory=="1"){
			return callback("1");
		}else{
			var query = new AV.Query('Shop_shop_type');
			query.equalTo("objectId", shopCategory);
			query.first({
				success : function(object) {
					return callback(object);
				},error:function(error){
					return callback(null);
				}
			});
		}
	}
}
/**
 * 删除商品样式图
 * @param goodObj
 * @param callback
 */
function delGoodsPics(goodObj,callback){
	var query = new AV.Query('Shop_goodsPic');
	query.equalTo("goodsOId", goodObj.id);
	query.destroyAll({
		   success: function(){
		     return callback(1);
		   },
		   error: function(err){
			   return callback(0);
		   }
	});
}
/**
 * 保存商品样式图
 * @param goodObj
 * @param pics 样式图数组
 * @param callback
 */
function saveGoodsPics(goodObj,pics,callback){
	var shopGoodsPicsArry=[];
	var picIds=[];
	for ( var i = 0; i < pics.length; i++) {
		picIds.push(pics[i]["objectId"]);
	}
	var ShopGoodsPic = common.getEntity("Shop_goodsPic");
	for ( var i = 0; i < picIds.length; i++) {
		var shopGoodsPic = new ShopGoodsPic();
		shopGoodsPic.set("goodsOId", goodObj.id);
		shopGoodsPic.set("picName", picIds[i]);
		shopGoodsPic.set("sortNum",i+1);
		shopGoodsPicsArry.push(shopGoodsPic);
	}
	 AV.Object.saveAll(shopGoodsPicsArry, function(list, error) {
		 var count=0;
		 if(list){
			 goodObj.set("picArray",shopGoodsPicsArry);
			 goodObj.save();
			 count=list.length;
		 }
		 return callback(error,count);
	 });
}
//保存更新商品图片
function saveOrUpdateGoodsPics(goodObj,pics,callback){
	var shopGoodsPicsArry=[];
	var picIds=[];
	for ( var i = 0; i < pics.length; i++) {
		picIds.push(pics[i]["objectId"]);
	}
	//查询已存在
	 var goodsPicQuery = new AV.Query('Shop_goodsPic');
	 goodsPicQuery.equalTo("goodsOId", goodObj.id);
	 goodsPicQuery.find({
		 success: function(picObjs) {
		 var updateIdsArray=[];
		 var delArray=[];
	     for ( var i = 0; i < picObjs.length; i++) {
			if(picIds.indexOf(picObjs[i])>-1){
				picObjs[i].set("sort",picIds.indexOf(picObjs[i])+1);
				shopGoodsPicsArry.push(picObjs[i]);
				updateIdsArray.push(picObjs[i].id);
			}else{
				delArray.push(picObjs[i]);
			}
		}
	     AV.Object.destroyAll(delArray);
	     var ShopGoodsPic =common.getEntity("Shop_goodsPic");
		 for ( var i = 0; i < picIds.length; i++) {
		 	if(updateIdsArray.indexOf(picIds[i])<0){
		 		var shopGoodsPic = new ShopGoodsPic();
		 		shopGoodsPic.set("goodsOId", goodObj.id);
		 		shopGoodsPic.set("picName", picIds[i]);
		 		shopGoodsPic.set("sortNum",i+1);
		 		shopGoodsPicsArry.push(shopGoodsPic);
		 	}
		 }
		AV.Object.saveAll(shopGoodsPicsArry, function(list, error) {
			 var count=0;
			 if(list){
				 goodObj.set("picArray",shopGoodsPicsArry);
				 goodObj.set("picName",shopGoodsPicsArry[0].get("picName"));
				 goodObj.save();
				 count=list.length;
			 }
			 return callback(error,count);
		});
	     },error:function(err){
	    	 return callback(err.message,null);
	     }
	    })
		
}
/**
 * 删除商品型号
 * @param goodObj
 * @param callback
 */
function delModelStocks(goodObj,callback){
	var query = new AV.Query('Shop_goods_model_stock');
	query.equalTo("goodsOId", goodObj.id);
	query.destroyAll({
		   success: function(){
		     return callback(1);
		   },
		   error: function(err){
			   return callback(0);
		   }
	});
}
/**
 * 保存商品库存和型号
 * @param goodObj 商品对象
 * @param picOId 图片标识
 * @param callback
 * @returns
 */
function saveModelStocks(goodObj,modelStocks,callback){
	var maxStock=0;
	//查询旧型号
	var query = new AV.Query('Shop_goods_model_stock');
	query.equalTo("goodsOId", goodObj.id);
	var saveObjs=[];
	var delObjs=[];
	var modelIdObjs={};
	var newModelIdObjs={};
	query.find({
		   success: function(goodsModelObjs){
			   for ( var i = 0; i < goodsModelObjs.length; i++) {
				   modelIdObjs[goodsModelObjs[i].get("model")]=goodsModelObjs[i];
			   }
			   for ( var j = 0; j < modelStocks.length; j++) {
			        newModelIdObjs[modelStocks[j]["model"]]=modelStocks[j];
				   	if(modelIdObjs[modelStocks[j]["model"]]!=null){
				   		modelIdObjs[modelStocks[j]["model"]].set("stock",parseInt(modelStocks[j]["stock"]));
				   		modelStocks[j]=null;
				   	}else{
				   		var ShopGoodsModelStock = common.getEntity("Shop_goods_model_stock");
				   		var shopGoodsModelStock = new ShopGoodsModelStock();
				   		shopGoodsModelStock.set("goodsOId", goodObj.id);
				   		shopGoodsModelStock.set("model", modelStocks[j]["model"]);
				   		shopGoodsModelStock.set("stock",parseInt(modelStocks[j]["stock"]));
				   		shopGoodsModelStock.set("sortNum",j+1);
				   		saveObjs.push(shopGoodsModelStock);
				   	}
			   }
			  
			   for ( var i = 0; i < goodsModelObjs.length; i++) {
			      if(newModelIdObjs[goodsModelObjs[i].get("model")]==null){
			   	   delObjs.push(goodsModelObjs[i]);
			      }
			   }			  
			   for ( var j = 0; j < goodsModelObjs.length; j++) {
				   if(newModelIdObjs[goodsModelObjs[j].get("model")]!=null)
					   saveObjs.push(goodsModelObjs[j]);
			   }
			   
			   if(saveObjs.length>0){
				   for ( var i = 0; i < saveObjs.length; i++) {
					if(saveObjs[i].get("stock")>99999999)
						saveObjs[i].set("stock",99999999);
					if(saveObjs[i].get("stock")<0)
						saveObjs[i].set("stock",0);
					saveObjs[i].set("goodsObj",{"__type":"Pointer",className:"Shop_goods",objectId:goodObj.id});
				   }
				  
				 AV.Object.saveAll(saveObjs, function(list, error) {
					 var count=0;
					 if(list){
						 if(delObjs.length>0)
							 AV.Object.destroyAll(delObjs);
						 for ( var i = 0; i < list.length; i++) {
							 
								maxStock+=list[i].get("stock");
							}
						//更新商品库存(所有型号存库总和)
						goodObj.set("stock",maxStock);
						goodObj.set("modelArray",saveObjs);
						goodObj.save(null, {
							success : function(newGoodsObj) {
							},error:function(errObj,err){
							}
						});
					 }else{
					 }
					 return callback(error,count);
				 });
			  }else{
				  return callback(null,maxStock);
			  }
		   },error:function(error){
			   return callback(error,maxStock);
		   }
	});
}
exports.findShopByUserOId = findShopByUserOId;
/**
 * 根据用户标识查询店铺对象
 * @param userOId
 * @param callback
 * @returns
 */
function findShopByUserOId(userOId,callback){
	if(userOId==""||userOId==null){
		return callback(null);
	}else{
		var query = new AV.Query('Shop_shop');
		query.equalTo("userOId", userOId);
		query.first({
			success : function(object) {
				return callback(object);
			},error:function(error){
				return callback(null);
			}
		});
	}
}
/**
 * 卖家商品列表
 * @param name 商品名称
 * @param page 页数
 * @param orderByType 排序序号，1价格升序、2价格降序、3销量升序、4销量降序、5库存升序、6库存降序、7添加时间升序、8添加时间降序
 * @param onOrOff 上架或下架，0下架，1上架，不传为全部
 * @param shopType 店铺类型标识
 * @param callback
 */
function sellerListGoods(uId,name,page,orderByType,onOrOff,shopType,callback){
	if(page==null||page==""||page==undefined){
		page="1";
	}
	page=parseInt(page);
	if(page<1)
		page=1;
	var goodsQuery = new AV.Query('Shop_goods');
	if(orderByType!=""&&orderByType!=null&&orderByType!="undefined"){
		orderByType=parseInt(orderByType);
		if(orderByType==1){
			goodsQuery.ascending("price");
		}else if(orderByType==2){
			goodsQuery.descending("price");
		}else if(orderByType==3){
			goodsQuery.ascending("saleNums");
		}else if(orderByType==4){
			goodsQuery.descending("saleNums");
		}else if(orderByType==5){
			goodsQuery.ascending("stock");
		}else if(orderByType==6){
			goodsQuery.descending("stock");
		}else if(orderByType==7){
			goodsQuery.ascending("createdAt");
		}else if(orderByType==8){
			goodsQuery.descending("createdAt");
		}
	}else{
		goodsQuery.ascending("createdAt");
	}
	if(onOrOff==null)
		onOrOff="";
	else
		onOrOff=onOrOff.toString();
	if(onOrOff!=""&&onOrOff!=null){
		onOrOff=parseInt(onOrOff);
		goodsQuery.equalTo("status", onOrOff);
	}else{
		goodsQuery.containedIn("status", [0,1]);
	}
	if(shopType!=null&&shopType!=""){
		goodsQuery.equalTo("shopCategory", shopType);
	}
	if(name!=null&&name!=""){
		goodsQuery.contains("title", name);
	}
	var num=10;
	goodsQuery.skip((page-1)*num);
	goodsQuery.limit(num);
	goodsQuery.equalTo("sellerOId", uId);
	goodsQuery.count({
		success : function(count) {
			goodsQuery.find({
				success : function(goodsObjs) {
					var goodsArry=[];
					for ( var i = 0; i < goodsObjs.length; i++) {
						goodsArry.push(common.getSellerGoodsInfo(goodsObjs[i]));
					}
					var result={};
					result["goods"]=goodsArry;
					result["currentPage"]=page;
					result["allCount"]=count;
					var returnArr=common.getReturnArr("","1000","",result);
					return callback(null,JSON.stringify(returnArr));
				}
			});
		},error: function(error) {
			return callback(null,JSON.stringify(common.getErrArr(error)));
		  }
	});
}
exports.getListShop = getListShop;
function getListShop(goodType,cb){
	if(goodType==""){
		var goodTypeObj={};
		goodTypeObj["name"]="其他分类";
		goodTypeObj["sortNum"]=999;
		return cb(null,goodTypeObj);
	}else{
		var query = new AV.Query('Shop_shop_type');
		query.equalTo("objectId",goodType);
	    query.first({
	    	success : function(shopTypeObj) {
	    		if(shopTypeObj==null){
	    			return cb("不存在的商品分类",null);
	    		}else{
		    		var goodTypeObj={};
		    		goodTypeObj["name"]=shopTypeObj.get("name");
		    		goodTypeObj["sortNum"]=shopTypeObj.get("sortNum");
		    		return cb(null,goodTypeObj);
	    		}
	    	}
	    })
	}
}
exports.listShopTypeCommon = listShopTypeCommon;
function listShopTypeCommon(shopOId,cb){
	var query = new AV.Query('Shop_shop_type');
	query.equalTo("shopOId",shopOId);
	query.ascending("sortNum");
    query.find({
    	success : function(shopTypeObjs) {
    		var shopTypeArry=[];
    		for ( var i = 0; i < shopTypeObjs.length; i++) {
    			var shopTypeObj=common.getShopTypeInfo(shopTypeObjs[i]);
    			shopTypeObj["goodsNum"]=0;
    			shopTypeObj["shopOId"]=shopOId;
    			shopTypeArry.push(shopTypeObj);
			}
    		var nullShopObj={};
    		nullShopObj["objectId"]="";
    		nullShopObj["name"]="其他分类";
    		nullShopObj["sortNum"]="999";
    		nullShopObj["goodsNum"]=0;
    		nullShopObj["createdTime"]=0;
    		nullShopObj["updatedTime"]=0;
    		nullShopObj["shopOId"]=shopOId;
    		shopTypeArry.push(nullShopObj);
    		async.eachSeries(shopTypeArry, function (shopType, callback) {
    			var goodsQuery = new AV.Query('Shop_goods');
	    		goodsQuery.equalTo("shopOId",shopOId);
	    		goodsQuery.equalTo("status",1);
	    		if(shopType["objectId"]==""){
	    			goodsQuery.equalTo("shopCategory","");
	    		}else{
	    			goodsQuery.equalTo("shopCategory",shopType["objectId"]);
	    		}
	    		goodsQuery.count({
			    	success : function(count) {
			    		shopType["goodsNum"]=count;
			    		callback(null);
			    	}
	    		})
			}, function (err) {
				if(err){
					return cb(err,null);
				}
				else{
					return cb(null,shopTypeArry);
				}
			});
    	},
    	error: function(error) {
			return callback(error,null);
		}
    });
}
/**
 * 店铺分类列表
 * @param uId
 * @param callback
 */
function listShopType(uId,callback){
	//查询是否拥有店铺
	findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			listShopTypeCommon(shopObj.id,function(err,shopTypeArry){
				var returnArr="";
				if(err){
					 returnArr=common.getErrArr(err);
				}else{
					 returnArr=common.getReturnArr("","1000","",shopTypeArry);
				}
				return callback(null,JSON.stringify(returnArr));
			})			    	
		}
	});
}
/**
 * 添加店铺分类
 * @param uId
 * @param name
 * @param callback
 */
function addShopType(uId,name,callback){
	//查询是否拥有店铺
	findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			//查询已有分类条数
			var query = new AV.Query('Shop_shop_type');
			query.equalTo("shopOId",shopObj.id);
			query.count({
				success : function(count) {
					if(apis['shopType']['maxNum']<=count){
						return callback(null,JSON.stringify(common.getErrArr("最多只能创建"+apis['shopType']['maxNum']+"个商品分类！")));
					}else{
						//查询是否重复
						query.equalTo("name",name);
					    query.first({
					    	success : function(shopTypeObj) {
					    		if(shopTypeObj!=null){
					    			return callback(null,JSON.stringify(common.getErrArr(name+"已经被使用了！")));
					    		}else{
					    			var ShopShopType = common.getEntity("Shop_shop_type");
									var shopShopType = new ShopShopType();
									shopShopType.set("shopOId", shopObj.id);
									shopShopType.set("name", name);
									shopShopType.set("sortNum", count+1);
									shopShopType.save(null, {
										success : function(shopShopType) {
											var result={};
											result["objectId"]=shopShopType.id;
											result["name"]=shopShopType.get("name");
											result["sortNum"]=shopShopType.get("sortNum");
											var returnArr=common.getReturnArr("1","1000","",result);
											return callback(null,JSON.stringify(returnArr));
										},error:function(errorObj,err){
											return callback(null,JSON.stringify(common.getErrArr(err)));
										}
									});
					    		}
					    	},error:function(err){
								return callback(null,JSON.stringify(common.getErrArr(err)));
							}
					    });
					}
				},error:function(err){
					return callback(null,JSON.stringify(common.getErrArr(err)));
				}
			});
		}
	});
}
/**
 * 修改店铺分类
 * @param uId
 * @param name
 * @param objectId
 * @param callback
 */
function editShopType(uId,name,objectId,callback){
	name = common.formatParams(name);
	//查询是否拥有店铺
	findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			//查询修改对象
			var query = new AV.Query('Shop_shop_type');
			query.equalTo("shopOId",shopObj.id);
			query.equalTo("objectId",objectId);
			query.first({
				success : function(oldShopTypeObj) {
					if(oldShopTypeObj==null){
						return callback(null,JSON.stringify(common.getErrArr("要编辑的对象不存在")));
					}else{
						if(oldShopTypeObj.get("name")==name){
							return callback(null,JSON.stringify(common.getErrArr("对象无任何改动")));
						}else{
			    			//查询是否重复
			    			var queryShopType = new AV.Query('Shop_shop_type');
			    			queryShopType.equalTo("name",name);
			    			queryShopType.equalTo("shopOId",shopObj.id);
			    			queryShopType.first({
						    	success : function(shopTypeObj) {
						    		if(shopTypeObj){
						    			return callback(null,JSON.stringify(common.getErrArr("您已经有这个名称的店铺分类了")));
						    		}else{
						    			oldShopTypeObj.set("name", name);
						    			oldShopTypeObj.save(null, {
											success : function(shopShopType) {
												var result={};
												result["objectId"]=shopShopType.id;
												result["name"]=shopShopType.get("name");
												result["sortNum"]=shopShopType.get("sortNum");
												var returnArr=common.getReturnArr("1","1000","",result);
												return callback(null,JSON.stringify(returnArr));
											},error:function(errorObj,err){
												return callback(null,JSON.stringify(common.getErrArr(err)));
											}
										});
						    		}
						    	},error:function(err){
									return callback(null,JSON.stringify(common.getErrArr(err)));
								}
						    });
						}
					}
				},error:function(err){
					return callback(null,JSON.stringify(common.getErrArr(err)));
				}
			});
		}
	});
}
/**
 * 删除店铺分类
 * @param uId
 * @param objectId
 * @param callback
 */
function delShopType(uId,objectId,callback){
	//查询是否拥有店铺
	findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
				//查询修改对象
				var query = new AV.Query('Shop_shop_type');
				query.equalTo("shopOId",shopObj.id);
				query.equalTo("objectId",objectId);
			    query.first({
			    	success : function(shopTypeObj) {
			    		if(shopTypeObj==null){
			    			return callback(null,JSON.stringify(common.getErrArr("要删除的对象不存在")));
			    		}else{
			    			if(shopTypeObj.get("shopOId")==shopObj.id){
				    			//删除分类对象
				    			shopTypeObj.destroy({
				    				  success: function(delShopTypeObj) {
				    					  var returnArr=common.getReturnArr("1","1000","","");
										  return callback(null,JSON.stringify(returnArr));
				    				  },
				    				  error: function(error) {
				    				  }
				    			});
			    			}else{
			    				return callback(null,JSON.stringify(common.getErrArr("无权操作")));
			    			}
			    		}
			    	},error:function(err){
						return callback(null,JSON.stringify(common.getErrArr(err)));
					}
			    });
		}
	})
}
/**
 * 返利比例
 * @param request
 * @param callback
 * @returns
 */
function promoteList(request,callback){
	var money=request.params.money;
	if(money==null||money==undefined)
		money=0;
	money=common.formatMoney(money);
	var max=100;
	var promote=[];
	var promoteMoney=[];
	var promoteMap=null;
	for(var i = 0; i <= max; i++){
		promote.push(i);
		promoteMap={};
		promoteMap["num"]=i;
		promoteMap["money"]=common.formatMoney(money*i/100);
		promoteMoney.push(promoteMap); 
	}
	var result={};
	result["promote"]=promote;
	result["promoteMap"]=promoteMoney;
	var returnArr=common.getReturnArr("1","1000","",result);							
	return callback(null,JSON.stringify(returnArr));
}

//删除商品分类业务
AV.Cloud.afterDelete('Shop_shop_type', function(request) {
	//删除后将商品中关联此对象的商品修改为无商品分类
		var query = new AV.Query('Shop_goods');
		query.equalTo("shopCategory",request.object.id);
		query.limit(999);
	    query.find({
	    	success : function(goodsObjs) {
	    		if(goodsObjs.length>0){
		    		for ( var i = 0; i < goodsObjs.length; i++) {
		    			goodsObjs[i].set("shopCategory","");
					}
		    		 AV.Object.saveAll(goodsObjs, function(list, error) {
					 });
	    		}
	    	},
	    	error: function(error) {
			  }
	    });
});

//添加商品
AV.Cloud.define("addGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品图片不能为空"]=request.params.pics;
		params["商品标题不能为空"]=request.params.title;
		params["商品价格不能为空"]=request.params.price;
		params["型号与库存不能为空"]=request.params.modelStocks;
		params["系统分类不能为空"]=request.params.goodType;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			addGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//前往编辑商品
AV.Cloud.define("goEditGoods",function(request, response) {
	//必填项：图片、标题、价格、型号库存、系统商品类型
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品标识不能为空"]=request.params.goodsOId;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			goEditGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//编辑商品
AV.Cloud.define("editGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品图片不能为空"]=request.params.pics;
		params["型号与库存不能为空"]=request.params.modelStocks;
//		params["系统分类不能为空"]=request.params.goodType;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			editGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//删除商品
AV.Cloud.define("delGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品标识不能为空"]=request.params.goodsOIds;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			delGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//下架商品
AV.Cloud.define("offGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品标识不能为空"]=request.params.goodsOIds;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			offGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//上架商品
AV.Cloud.define("onGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["商品标识不能为空"]=request.params.goodsOIds;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			onGoods(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
		}
	}
});
//商品列表
AV.Cloud.define("sellerListGoods",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		sellerListGoods(request.user.id,request.params.name,request.params.page,request.params.orderByType,request.params.onOrOff,request.params.shopType,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
	}
});
//店铺分类列表
AV.Cloud.define("listShopType",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		listShopType(request.user.id,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
	}
});
//添加店铺分类
AV.Cloud.define("addShopType",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["分类名称不能为空"]=request.params.name;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			addShopType(request.user.id,request.params.name,function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});
		}
	}
});
//修改店铺分类
AV.Cloud.define("editShopType",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["分类标识不能为空"]=request.params.objectId;
		params["分类名称不能为空"]=request.params.name;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			editShopType(request.user.id,request.params.name,request.params.objectId,function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});
		}
	}
});
//删除店铺分类
AV.Cloud.define("delShopType",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
		var params={};
		params["分类标识不能为空"]=request.params.objectId;
		var msg=common.validateParamsEmpty(params);
		if(msg!=null){
			return response.success(JSON.stringify(common.getErrArr(msg)));
		}
		else{
			delShopType(request.user.id,request.params.objectId,function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
			});
		}
	}
});
//分成比例
AV.Cloud.define("promoteList",function(request, response) {
	if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");
	}else{
	      promoteList(request,function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
	}
});
